<template>
  <view class="page pageBg-color">

    <view class="menu-tabs">
      <uni-segmented-control :current="currentIndex" :values="tabsValues" @clickItem="onMenuItem" styleType="button"
        activeColor="#007aff"></uni-segmented-control>
    </view>

    <list-cutePet :dataList="currentList" :isLoading="currentCate.isLoading" :isHasMore="currentCate.isHasMore"
      :isEmpty="currentCate.isEmpty" />

    <com-backTop :fixed="fixed"></com-backTop>

  </view>
</template>


<script lang="ts" setup>
import { ref, computed } from 'vue';
import { onLoad, onPullDownRefresh, onReachBottom, onPageScroll } from '@dcloudio/uni-app';
import { API } from "@/services/api";

const currentIndex = ref(0); // 被激活的 tabIndex
const tabsValues = computed(() => cateList.value.map(item => item.title)); // 计算属性 + map 返回新的 tabs 数组
const tabsType = ref("all"); // 宠物的类型值

const cateList = ref([
  {
    title: "全部",
    type: "all",
    pageNo: 1,
    list: [],
    isLoading: false,
    isHasMore: true,
    isEmpty: false,
  },
  {
    title: "猫猫",
    type: "cat",
    pageNo: 1,
    list: [],
    isLoading: false,
    isHasMore: true,
    isEmpty: false,
  },
  {
    title: "狗狗",
    type: "dog",
    pageNo: 1,
    list: [],
    isLoading: false,
    isHasMore: true,
    isEmpty: false,
  }
]);
const currentCate = computed(() => cateList.value[currentIndex.value]); // 当前激活的分类项的所有数据
const currentList = computed(() => currentCate.value.list); // 当前激活的分类的列表数据

const fixed = ref(false); // 刷新、返回顶部 按钮的显示

// 
onLoad(() => {
  getData();
});

//  
onPullDownRefresh(() => {
  onRefresh();
});

// 
onReachBottom(() => {
  if (currentCate.value.isHasMore) getData();
});

//  
onPageScroll((e) => {
  fixed.value = e.scrollTop > 200;
});

// 
const onRefresh = () => {
  let obj = cateList.value[currentIndex.value];
  obj.list = [];
  obj.pageNo = 1;
  getData();
};

// 
const getData = () => {
  let obj = cateList.value[currentIndex.value];
  obj.isLoading = true;

  API.petShow(tabsType.value, obj.pageNo, 12)
    .then((res: any) => {
      console.log(`~~~获取 ${obj.title} 类型 page = ${obj.pageNo} 的数据`);
      let newList = [...obj.list];
      if (obj.pageNo === 1) newList = [];
      obj.list = newList.concat(res.data || []);
      obj.isLoading = false;
      obj.isHasMore = res.data && res.data.length >= 12;
      obj.isEmpty = obj.list.length <= 0;
      obj.pageNo++;
    })
    .catch(() => {
      obj.isLoading = false;
      obj.isHasMore = false;
      obj.isEmpty = true;
    })
};

// 
const onMenuItem = (e: any) => {
  currentIndex.value = e.currentIndex;
  tabsType.value = cateList.value[currentIndex.value].type;
  if (cateList.value[currentIndex.value].list.length <= 0) getData();
  console.log("~~~点击选项栏获取分类数据", currentIndex.value, tabsType.value);
};

</script>


<style lang="scss" scoped>
@use "style.scss";
</style>